package com.jt.www.admin.market.controller;

import com.google.common.base.Function;
import com.google.common.collect.Lists;
import com.jt.www.admin.market.service.InsidePerformanceService;
import com.jt.www.admin.order_pc.service.ExportConfigService;
import com.jt.www.domain.dto.InsidePerformanceOutputDTO;
import com.jt.www.domain.enums.common.ExportChannelTypeEnum;
import com.jt.www.domain.enums.common.YesOrNoEnum;
import com.jt.www.domain.enums.wxb.PerformanceSendStatusEnum;
import com.jt.www.domain.po.ExportConfigEntity;
import com.jt.www.domain.po.InsidePerformance;
import com.jt.www.domain.qo.InsidePerformanceQO;
import com.jt.www.model.reps.GenericDataResponse;
import com.jt.www.model.reps.GenericListResponse;
import com.jt.www.model.reps.GenericResponse;
import com.jt.www.util.excel.CsvExportUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.apache.commons.collections.CollectionUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.OutputStream;
import java.util.List;

/**
 * 内部人员业绩
 * Created by shaoyn on 2020/07/21.
 */
@Api(value = "内部人员业绩相关接口", tags = {"INSIDE-PERFORMANCE-API"}, description = "内部人员业绩")
@RestController
@RequestMapping(value = "/performance")
public class InsidePerformanceController {
    public static final Logger log = LoggerFactory.getLogger(InsidePerformanceController.class);

    @Autowired
    private InsidePerformanceService insidePerformanceService;
    @Autowired
    private ExportConfigService exportConfigService;

    /**
     * 内部人员业绩
     *
     * @return
     */
    @ApiOperation(value = "内部人员业绩列表", notes = "内部人员业绩列表", httpMethod = "POST")
    @PostMapping(value = "/queryInsidePerformance", produces = {MediaType.APPLICATION_JSON_UTF8_VALUE})
    public ResponseEntity<GenericListResponse<InsidePerformance>> queryInsidePerformance(@RequestBody InsidePerformanceQO insidePerformanceQO) {
        return insidePerformanceService.queryInsidePerformance(insidePerformanceQO);
    }

    @ApiOperation(value = "导出内部人员业绩列表", notes = "导出内部人员业绩列表")
    @GetMapping(value = "/downList/{processSendStatus}", produces = {MediaType.APPLICATION_JSON_UTF8_VALUE})
    public void downList(@ApiParam(value = "将批量导出数据全部标记为已发放 YES:是 N0:否", required = true)
                         @PathVariable(value = "processSendStatus") YesOrNoEnum processSendStatus,
                         InsidePerformanceQO insidePerformanceQO, HttpServletResponse response) {
        String findCode = "EDU_" + System.currentTimeMillis();
        OutputStream os = null;
        try {
            if (YesOrNoEnum.YES.equals(processSendStatus)) {
                //批量修改状态
                insidePerformanceService.updateSendStatus(insidePerformanceQO, PerformanceSendStatusEnum.SEND.getStatus());
            }
            //查询导出配置
            ExportConfigEntity exportConfigEntity = exportConfigService.getExportConfig(ExportChannelTypeEnum.INSIDE_PERFORMANCE.getCode());
            if (null == exportConfigEntity) {
                return;
            }
            String fileName = exportConfigEntity.getFileName();

            os = response.getOutputStream();
            CsvExportUtil.responseSetProperties(fileName, response);
            //模板位置
            String titles = exportConfigEntity.getTitles();
            CsvExportUtil.setTitles(titles, os);
            List<InsidePerformance> appList;
            int pn = 1;
            insidePerformanceQO.setPn(pn);
            insidePerformanceQO.setPs(CsvExportUtil.MAX_PAGE_SIZE);
            String[] keyArr = exportConfigEntity.getKeyArr().split(",");

            //分批查询并生成数据插入到导出文件中
            while (CollectionUtils.isNotEmpty(appList = insidePerformanceService.queryInsidePerformance(insidePerformanceQO).getBody().getList())) {
                List list = Lists.transform(appList, (Function<InsidePerformance, Object>) insidePerformance -> new InsidePerformanceOutputDTO(insidePerformance));
                CsvExportUtil.doExport(list, keyArr, os);
                insidePerformanceQO.setPn(++pn);
                if (insidePerformanceQO.getPs() > appList.size()) {
                    break;
                }
            }
        } catch (Exception e) {
            log.error("{}导出{}发生错误:", findCode, e);
        } finally {
            if (os != null) {
                try {
                    os.close();
                } catch (IOException e) {
                }
            }
        }
    }

    /**
     * 标记发放状态
     *
     * @return
     */
    @ApiOperation(value = "标记发放状态", notes = "标记发放状态", httpMethod = "POST")
    @PostMapping(value = "/updateSendStatus/{id}/{sendStatus}", produces = {MediaType.APPLICATION_JSON_UTF8_VALUE})
    public ResponseEntity updateSendStatus(@ApiParam(value = "id", required = true) @PathVariable Long id,
                                           @ApiParam(value = "标记发放状态 1-已发放，2-未发放", required = true) @PathVariable String sendStatus) {
        InsidePerformanceQO insidePerformanceQO = new InsidePerformanceQO();
        insidePerformanceQO.setId(id);
        if (insidePerformanceService.updateSendStatus(insidePerformanceQO, sendStatus) > 0) {
            return GenericDataResponse.ok();
        } else {
            return GenericDataResponse.errorWithMsg("修改失败!");
        }
    }


    /**
     * 内部人员业绩推荐人重新设置
     *
     * @return
     */
    @ApiOperation(value = "内部人员业绩推荐人重新设置", notes = "内部人员业绩推荐人重新设置", httpMethod = "POST")
    @PostMapping(value = "/updateInsidePerformanceManager", produces = {MediaType.APPLICATION_JSON_UTF8_VALUE})
    public ResponseEntity<GenericResponse> updateInsidePerformanceManager(@ApiParam(value = "投保单号(逗号分割)") @RequestParam String ids) {
        return insidePerformanceService.updateInsidePerformanceManager(ids);
    }


}
